#include "../../ExEngine/math/matrix.h"

#include "../../ExEngine/physics/actor.h"
#include "../../ExEngine/physics/physics.h"
#include "../../ExEngine/math/quaternion.h"
#include "../../ExEngine/common/util.h"
#include "../../ExEngine/engine/engine.h"
#include "../../ExEngine/engine/camera.h"
#include "../../ExEngine/render/d3d_mesh.h"
#include "../../ExEngine/render/d3d.h"
#include "../../ExEngine/sound/dsound.h"
#include "../../ExEngine/input/dinput.h"

#include "ent_fallbridge.h"
#include "player.h"
#include "../game/core.h"

/**********************************************************************
 *
 **********************************************************************/

CFallBridge::CFallBridge() : CObject()
{
	m_isValid = true;
	m_isFalling = false;
}

HRESULT CFallBridge::Create()
{		
	CActor::ActorData data;
	data.initalTransform = m_transform;
	data.mass = 10.0f;
	data.friction = 0.0125f;
	data.restitution = 0.2f;
	data.maxForce = 200.0f;
	data.maxSlope = PI / 5.0f;

	if(FAILED(CEngine::GetInstance()->GetPhysics()->CreateActor("fall_bridge.HKX", &m_pPhysics, data, this)))
	{
		Release();
		return E_FAIL;
	}

	if(FAILED(CEngine::GetInstance()->GetRenderer()->CreateModel("fall_bridge.mdl", &m_pModel)))
	{
		Release();
		return E_FAIL;
	}
	m_pPhysics->SetStill(true);
	m_pPhysics->SetCollisionCallback(Game::g_Player);
	m_pModel->setRenderFlags(RENDER_DEFAULT);

	m_FallTimer.Set(1.0f);

	return S_OK;
}

HRESULT CFallBridge::Release()
{	
	HRESULT result = S_OK;
	if(m_pModel)
	{
		m_pModel = NULL;
	}
	if(m_pPhysics)
	{
		CPhysics* pPhysics = CEngine::GetInstance()->GetPhysics();
		if(FAILED(pPhysics->ReleaseActor(m_pPhysics)))
			result = E_FAIL;
		m_pPhysics = NULL;
	}
	return result;
}

void CFallBridge::Idle()
{
}

void CFallBridge::setPosition(const Vector3f &position)
{
	m_transform = Matrix4f::identity();
	m_transform.SetTranslation(position); 
	if(m_pPhysics)
		m_pPhysics->SetTransform(m_transform);
	
}

void CFallBridge::OnCollisionEvent(const Vector3f& contactPoint, const Vector3f& contactNormal, CObject* pOtherObject) {

	if(pOtherObject == Game::g_Player)
	{
		if(!m_FallTimer.IsActive())
			m_FallTimer.Start();
	}
}

bool CFallBridge::isValid() {
	return m_isValid;
}

void CFallBridge::Update(const float dt)
{
	if(!m_isFalling) { 
		m_FallTimer.Update(dt);
		if(m_FallTimer.IsComplete()) {
			
			m_pPhysics->SetStill(false);
			m_isFalling = true;
		}
	}
	else
	{
		m_transform = m_pPhysics->GetTransform();
	}
}

void CFallBridge::Draw()
{	
	//GetRenderer()->DrawSphere(m_transform.Translation());
//	CEngine::PrintVector(m_transform.Translation(), "FB");
	if(m_pModel)
		m_pModel->Draw(m_transform,m_velocity);

}